package com.bds.portal.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bds.model.Hosts;
import com.bds.model.Result;
import com.bds.model.Template;
import com.bds.model.TemplateDetail;
import com.bds.portal.common.result.Page;
import com.bds.portal.common.result.USession;
import com.bds.portal.service.HostService;
import com.bds.portal.service.MyService;
import com.bds.portal.service.TempletService;
import com.bds.portal.service.UserService;
import com.bds.portal.util.Const;

import shaded.org.apache.commons.lang3.StringUtils;

@Controller
@RequestMapping("/action/my")
public class SnatchAction extends BaseAction {
	private static Logger logger = Logger.getLogger(MyAction.class);
	@Resource
	private UserService userService;
	@Resource
	private MyService myService;

	@Resource
	private TempletService templetService;
	@Resource
	private HostService hostService;

	@RequestMapping(value = "/m/toTemplateConfig")
	public ModelAndView toTemplateConfig(HttpServletRequest request, HttpServletResponse response, Long pid, Long hid)
			throws Exception {

		ModelAndView view = new ModelAndView();
		try {

			if (pid == null && hid == null) {
				view.addObject("pid", "''");
				view.addObject("hid", "''");
			} else if (hid != null && pid == null) {
				Hosts host = hostService.getHosts(hid);
				view.addObject("pid", host.getProject_id());
				view.addObject("hid", host.getId());
			} else if (pid != null && hid == null) {
				view.addObject("pid", pid);
				view.addObject("hid", "''");
			} else {
				Hosts host = hostService.getHosts(hid);
				view.addObject("pid", host.getProject_id());
				view.addObject("hid", host.getId());
			}

			view.setViewName("/web/my/snatch/template.jsp");

		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
		return view;
	}

	@RequestMapping(value = "/m/getTemplateList")
	@ResponseBody
	public Page getTemplateList(HttpServletRequest request, HttpServletResponse response, Integer pageNum,
			Integer pageSize, Long pid, Long hid) throws Exception {
		Page page = new Page();
		try {
			USession us = this.getUserSession(request);
			page = myService.getMyConfigList(us.getId(), pageNum, pageSize, pid, hid);
		} catch (Exception e) {
			page.setCode(Const.FAIL_500);
			logger.error("", e);
		}
		return page;
	}

	@RequestMapping(value = "/m/toMyJob")
	public ModelAndView toMyJob(HttpServletRequest request, HttpServletResponse response, String request_id)
			throws Exception {

		ModelAndView view = new ModelAndView();
		try {

			Template t = myService.getTemplate(request_id);

			view.addObject("request_id", request_id);
			view.addObject("title", t.getTemplate_name());
			view.setViewName("/web/my/snatch/my_url.jsp?mid=a1&aid=ch11");

		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
		return view;
	}

	@RequestMapping(value = "/m/toMySnatch")
	public ModelAndView toMySnatch(HttpServletRequest request, HttpServletResponse response, Long hid)
			throws Exception {

		ModelAndView view = new ModelAndView();
		try {
			USession us = this.getUserSession(request);
			if (us != null) {
				List<Template> list = myService.getMyTemplateList(us.getId(), hid);
				String json = this.parseDateJson(list);
				view.addObject("tmpList", json);
			}
			Hosts h = hostService.getHosts(hid);
			if (h != null) {
				view.addObject("hname", h.getWebsite());
			}
			view.addObject("hid", hid);
			view.setViewName("/web/my/snatch/my_snatch.jsp");

		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
		return view;
	}

	@RequestMapping(value = "/m/addNewTmpl")
	@ResponseBody
	public Result addNewTmpl(HttpServletRequest request, HttpServletResponse response, Long pid, Long hid, String url,
			String tname) {
		Result ret = new Result();

		try {
			USession us = this.getUserSession(request);
			ret = myService.addNewTmpl(us.getId(), pid, hid, url, tname);
		} catch (Exception e) {
			ret.setResult(Const.FAIL, "保存异常");
		}

		return ret;
	}

	@RequestMapping(value = "/m/saveTemplateConfig")
	@ResponseBody
	public Result saveTemplateConfig(HttpServletRequest request, HttpServletResponse response, Template t) {
		Result ret = new Result();

		try {
			USession us = this.getUserSession(request);
			t.setUser_id(us.getId());
			if (StringUtils.isNotEmpty(t.getExts())) {
				// 规则：key|value,key|value 例如url|http://www.16.com
				String[] ary = t.getExts().split(",");
				for (String ar : ary) {
					if (ar.indexOf("|") < 0) {
						ret.setResult(Const.FAIL, "附加属性填写规则不对,请按照key|value,key|value 例如url|http://www.16.com");
						return ret;
					}
				}
			}

			if (t != null && t.getType() != null && t.getType().equals("list")) {
				if (StringUtils.isNotEmpty(t.getPage_rule())) {
					int index = t.getPage_rule().indexOf("[[");
					int last = t.getPage_rule().indexOf("]]");

					if (index >= 0 && last >= 0) {
						if (myService.saveTemplate(t, null)) {
							ret.setResult(Const.SUC, "操作成功");
						} else {
							ret.setResult(Const.FAIL, "请先保存模板");
						}
					} else {
						ret.setResult(Const.FAIL, "翻页规则配置错误");
					}
				} else {
					ret.setResult(Const.FAIL, "没有配置翻页规则");
				}

			} else {
				if (StringUtils.isEmpty(t.getContent())) {
					ret.setResult(Const.FAIL, "请添加链接");
					return ret;
				}
				String line = System.getProperty("line.separator");
				String[] array = t.getContent().split(line);
				if (array.length == 0) {
					ret.setResult(Const.FAIL, "请输入url");
					return ret;
				}

				if (array.length == 1) {
					array = t.getContent().split("\n");
					if (array.length == 1) {
						array = t.getContent().split("\r");
					}
				}
				if (myService.saveTemplate(t, array)) {
					ret.setResult(Const.SUC, "操作成功");
				} else {
					ret.setResult(Const.FAIL, "保存失败");
				}
			}

		} catch (Exception e) {
			ret.setResult(Const.FAIL, "保存异常");
		}

		return ret;
	}

	@RequestMapping(value = "/m/startTmplJob")
	@ResponseBody
	public Result startTmplJob(HttpServletRequest request, HttpServletResponse response, String tid) {
		Result ret = new Result();
		try {

			ret = myService.doStartJob(tid);
		} catch (Exception e) {
			logger.error("", e);
			ret.setResult(Const.FAIL, "启动任务失败");
		}
		return ret;
	}

	@RequestMapping(value = "/m/getTempDetail")
	@ResponseBody
	public Result getTempDetail(HttpServletRequest request, HttpServletResponse response, String request_id) {
		Result ret = new Result();
		try {

			List<TemplateDetail> list = myService.getTemplateDetailList(request_id);
			ret.setData(list);
			ret.setCode(Const.SUC);
		} catch (Exception e) {
			logger.error("", e);
			ret.setResult(Const.FAIL, "获取详情列表失败");
		}
		return ret;
	}
	//
	// @RequestMapping(value = "/m/getTempDetailById")
	// @ResponseBody
	// public Result getTempDetailById(HttpServletRequest request,
	// HttpServletResponse response, Long id) {
	// Result ret = new Result();
	// try {
	//
	// TemplateDetail detail = myService.getTemplateDetailById(id);
	// ret.setData(detail);
	// ret.setCode(Const.SUC);
	// } catch (Exception e) {
	// logger.error("", e);
	// ret.setResult(Const.FAIL, "获取详情失败");
	// }
	// return ret;
	// }
	//
	// @RequestMapping(value = "/m/upTempDetailOp")
	// @ResponseBody
	// public Result upTempDetailOp(HttpServletRequest request,
	// HttpServletResponse response, Long id, String op) {
	// Result ret = new Result();
	// try {
	// if (StringUtils.isNotEmpty(op)) {
	// if (op.equals("{}")) {
	// op = "";
	// }
	// }
	// ret = myService.upTempDetailOp(id, op);
	//
	// ret.setCode(Const.SUC);
	// } catch (Exception e) {
	// logger.error("", e);
	// ret.setResult(Const.FAIL, "操作失败");
	// }
	// return ret;
	// }
	//
	// @RequestMapping(value = "/m/upTempDetailEle")
	// @ResponseBody
	// public Result upTempDetailEle(HttpServletRequest request,
	// HttpServletResponse response, String request_id, Long id,
	// String cname, String ctype, String list_path, String node_path) {
	// Result ret = new Result();
	// try {
	//
	// ret = templetService.updTemplateDetailEle(id, request_id, cname, ctype,
	// list_path, node_path);
	//
	// ret.setCode(Const.SUC);
	// } catch (Exception e) {
	// logger.error("", e);
	// ret.setResult(Const.FAIL, "操作失败");
	// }
	// return ret;
	// }

}
